package com.huluobo.apps.pages

import android.os.Environment
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.apps.AppsIntent
import com.huluobo.apps.AppsViewModel
import com.huluobo.apps.entity.AppsEntity
import com.huluobo.apps.entity.AppsEntityItem
import com.huluobo.lib_base.BaseApp
import com.huluobo.lib_base.BaseLoadingDialog
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.StateType
import com.huluobo.lib_base.UIState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

/**
 *  Created by LC on 2025/6/23.
 */

@Composable
fun AppsPage(navHostController: NavHostController, vm: AppsViewModel = hiltViewModel()) {
    //compose页面中数据源的类型,它可以根据数据源的变化产生不同的状态,来实时刷新
    val list = remember {
        //快照的list,当list发生改变时,会刷新页面直接展示出新的数据
        SnapshotStateList<AppsEntityItem>()
    }

    //控制是否弹出进度条
    var isShowProgress by remember {
        mutableStateOf(false)
    }

    //控制是否弹出安装进度条
    var isShowLaunch by remember {
        mutableStateOf(false)
    }

    //安装的进度
    var currentProgress by remember {
        mutableStateOf(0f)
    }

    //控制更新进度的协程
    var scope = rememberCoroutineScope()

    //compose中开启协程的位置,key1 触发网络请求的条件,传递空为默认初始化时就触发
    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        isShowProgress = false
                        ToastUtils.showLong("获取应用程序列表失败:${it.msg}")
                        Log.e("TagA", "获取应用程序列表失败:${it.msg}")
                    }

                    UIState.OnLoading -> {
                        isShowProgress = true
                    }

                    is UIState.OnSuccess<*> -> {
                        isShowProgress = false
                        if (it.type == StateType.DEFAULT) {
                            list.clear()
                            //由于请求时Entity会强转为Any类型,这里需要强转回来
                            list.addAll(it.data as AppsEntity)
                        }

                        if (it.type == StateType.DOWNLOAD) {
                            ToastUtils.showLong("下载成功")
                        }
                    }
                }
            }
        }

        //初始化时发起意图
        vm.sendIntent(AppsIntent.GetApps)
    })

    if (isShowProgress) {
        BaseLoadingDialog()
    }

    Column(Modifier.padding(10.dp)) {
        BaseTitle(title = "在线应用", navHostController = navHostController)
        Spacer(modifier = Modifier.height(10.dp))
        LazyVerticalGrid(
            columns = GridCells.Fixed(2), content = {
                items(list) {
                    AppsItem(appsEntityItem = it, vm) {
                        isShowLaunch = true
                        scope.launch {
                            for (i in 1..100) {
                                currentProgress = i.toFloat() / 100
                                //延迟100毫秒更新一次进度
                                delay(100)
                            }
                            isShowLaunch = false
                            ToastUtils.showLong("安装成功")
                        }
                    }
                }
            }, verticalArrangement = Arrangement.spacedBy(20.dp), horizontalArrangement = Arrangement.spacedBy(20.dp)
        )
    }

    if (isShowLaunch) {
        AlertDialog(onDismissRequest = {}, confirmButton = {}, text = {
            Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
                LinearProgressIndicator(progress = currentProgress)
                Text(text = "${(currentProgress * 100).toInt()}/100")
            }
        }, title = {
            Text(text = "安装中...")
        })
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AppsItem(appsEntityItem: AppsEntityItem, vm: AppsViewModel, longClick: () -> Unit) {

    //获取系统文件夹
//    val file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)

    //通过app的context拿到app的文件路径,如果没有,会自动创建一个
    val file = BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

    var isShow by remember {
        mutableStateOf(false)
    }

    Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.combinedClickable(
        onClick = {
            isShow = true
        },
        onLongClick = {
            longClick()
        }
    )) {
        AsyncImage(
            model = appsEntityItem.appIcon,
            contentDescription = "",
            modifier = Modifier
                .fillMaxWidth()
                .size(80.dp),
            alignment = Alignment.Center
        )
        Text(text = "名称 : ${appsEntityItem.appName}", fontWeight = FontWeight.Bold)
        Text(text = "网址 : ${appsEntityItem.netUrl}", maxLines = 1, overflow = TextOverflow.Ellipsis)
        Text(
            text = "创建时间 : ${appsEntityItem.createTime.substring(0, 10)}",
            color = Color.LightGray,
            fontSize = 13.sp
        )
        Text(
            text = "更新时间 : ${appsEntityItem.updateTime.substring(0, 10)}",
            color = Color.LightGray,
            fontSize = 13.sp
        )
    }

    if (isShow) {
        AlertDialog(onDismissRequest = { isShow = false }, confirmButton = {
            TextButton(onClick = {
                vm.sendIntent(
                    AppsIntent.DownloadApk(
                        appsEntityItem.apkUrl,
                        //需要一个文件路径来生成一个文件
                        File(file, appsEntityItem.appName + ".apk")
                    )
                )
                isShow = false
            }) {
                Text(text = "确认")
            }
        }, dismissButton = {
            TextButton(onClick = {
                isShow = false
            }) {
                Text(text = "取消")
            }
        }, title = {
            Text(text = "下载提醒")
        }, text = {
            Text(text = "是否要下载${appsEntityItem.appName}吗?")
        })
    }
}